package com.xw.unification.config;

import com.xw.unification.condition.UnifiedRepeatableRequestCondition;
import com.xw.unification.entity.ControllerMappingUtil;
import com.xw.unification.handler.PathVersionHandlerMapping;
import com.xw.unification.condition.UnifiedApiVersionCondition;
import com.xw.unification.helper.ApiVersionHelper;
import com.xw.unification.interceptor.ApiVersionHelperResettingFilter;
import com.xw.unification.interceptor.RepeatableRequestFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;


/**
 * API 版本组件自动配置类
 *
 * @author qiwei
 * @date 2023-8-9 21:00:00
 * @since v1.0.0
 */
@Configuration
@AutoConfigureAfter({WebUnificationMvcBaseConfig.class})
@EnableConfigurationProperties({WebUnificationMvcProperties.class})
@Conditional(UnifiedApiVersionCondition.class)
public class WebUnificationMvcApiVersionConfig implements WebMvcRegistrations, ApplicationRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebUnificationMvcApiVersionConfig.class);

    private final PathVersionHandlerMapping handlerMapping;

    @Autowired
    public WebUnificationMvcApiVersionConfig(
            WebUnificationMvcProperties webUnificationMvcProperties) {
        this.handlerMapping = new PathVersionHandlerMapping(webUnificationMvcProperties.getApiVersion());
        ControllerMappingUtil.init(handlerMapping);
        LOGGER.info("[WebUnificationMvcRegistrationConfig] ### RegistrationConfig auto configuration");
    }

    @Override
    public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
        return handlerMapping;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        ControllerMappingUtil.initMapping();
    }

    @Bean
    @Conditional(UnifiedApiVersionCondition.class)
    public ApiVersionHelperResettingFilter apiVersionHelperResettingFilter() {
        LOGGER.info("[CustomerWebMvcConfig] ### ApiVersionHelperResettingFilter bean auto inject");
        return new ApiVersionHelperResettingFilter();
    }

}
